package com.uinnova.product.eam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.util.CollectionUtils;
import com.binary.core.exception.BinaryException;
import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.comm.exception.BusinessException;
import com.uinnova.product.eam.comm.model.CVcBaseConfig;
import com.uinnova.product.eam.comm.model.VcBaseConfig;
import com.uinnova.product.eam.service.BaseConfigService;
import com.uinnova.product.eam.service.es.BaseConfigDao;
import com.uinnova.product.vmdb.comm.i18n.MessageUtil;
import com.uino.dao.util.ESUtil;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 配置service实现类
 */
@Service
public class BaseConfigServiceImpl implements BaseConfigService {

    @Resource
    private BaseConfigDao baseConfigDao;

    /**
     * 查询配置列表
     *
     * @param cdt 查询条件
     * @return 配置列表
     */
    @Override
    public List<VcBaseConfig> queryBaseConfigList(CVcBaseConfig cdt) {
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        MessageUtil.checkEmpty(domainId, "domainId");
        if (BinaryUtils.isEmpty(cdt)) {
            cdt = new CVcBaseConfig();
        }
        cdt.setDomainId(domainId);
        cdt.setDataStatus(1);
        return baseConfigDao.getListByCdt(cdt);
    }

    /**
     * 配置类更新
     *
     * @param record {@link VcBaseConfig}
     * @return id
     */
    @Override
    public Long saveOrUpdateBaseConfig(VcBaseConfig record) {
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        MessageUtil.checkEmpty(domainId, "domainId");
        MessageUtil.checkEmpty(record, "record");
        MessageUtil.checkEmpty(record.getCfgCode(), "cfgCode");

        String loginCode = SysUtil.getCurrentUserInfo().getLoginCode();
        long time = ESUtil.getNumberDateTime();

        CVcBaseConfig config = new CVcBaseConfig();
        config.setDomainId(domainId);
        config.setCfgCode(record.getCfgCode());
        Page<VcBaseConfig> page = baseConfigDao.getListByCdt(1, 1, config);

        if (page.getTotalRows() == 0) {
            record.setCreator(loginCode);
            record.setCreateTime(time);
            record.setDataStatus(1);
            record.setId(null);
        } else {
            VcBaseConfig source = page.getData().get(0);
            BeanUtil.copyProperties(record, source, "id", "cfgCode", "domainId", "creator", "createTime");
            record = source;
            record.setModifier(loginCode);
        }

        record.setModifyTime(time);
        return baseConfigDao.saveOrUpdate(record);
    }

    /**
     * 查找激活的配置
     *
     * @param cfgCode 配置代码
     * @return {@link VcBaseConfig}
     */
    @Override
    public VcBaseConfig getSelectedConfig(String cfgCode) {

        BoolQueryBuilder searchQuery = QueryBuilders.boolQuery();
        searchQuery.must(QueryBuilders.termQuery("cfgCode.keyword", cfgCode));
        searchQuery.must(QueryBuilders.termQuery("selected", true));
        searchQuery.must(QueryBuilders.termQuery("dataStatus", 1));

        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("modifyTime").order(SortOrder.DESC);

        Page<VcBaseConfig> page = baseConfigDao.getSortListByQuery(1, 1, searchQuery,
                Collections.singletonList(fieldSortBuilder));

        if (page.getTotalRows() == 1) {
            return page.getData().get(0);
        }

        throw new BinaryException("没有找到激活的配置");
    }

    /**
     * 选择配置
     *
     * @param id 配置id
     */
    @Override
    public void selectConfig(Long id) {
        VcBaseConfig config = getNotDelConfigById(id);
        config.setSelected(true);
        config.setModifyTime(ESUtil.getNumberDateTime());
        baseConfigDao.saveOrUpdate(config);
    }

    /**
     * 删除配置
     *
     * @param id 配置id
     */
    @Override
    public void deleteConfig(Long id) {
        VcBaseConfig config = getNotDelConfigById(id);
        config.setDataStatus(0);
        baseConfigDao.saveOrUpdate(config);
    }

    @Override
    public List<VcBaseConfig> findBaseConfigList(List<String> cfgCodes) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termsQuery("cfgCode.keyword", cfgCodes));
        return baseConfigDao.getListByQuery(queryBuilder);
    }

    @Override
    public Long saveOrUpdateBaseConfigBatch(List<VcBaseConfig> baseConfigList) {
        if (CollectionUtils.isEmpty(baseConfigList)) {
            throw new BusinessException("配置不能为空!");
        }
        baseConfigList.forEach(baseConfig -> {
            if (baseConfig != null) {
                saveOrUpdateBaseConfig(baseConfig);
            }
        });
        return 1L;
    }

    private VcBaseConfig getNotDelConfigById(Long id) {
        CVcBaseConfig cdt = new CVcBaseConfig();
        cdt.setId(id);
        cdt.setDataStatus(1);
        Page<VcBaseConfig> list = baseConfigDao.getListByCdt(1, 1, cdt);
        if (list.getTotalRows() == 0) {
            throw new BinaryException("配置不存在");
        }
        return list.getData().get(0);
    }
}
